<template>
  <el-dialog  width="80%" class="cooperationDialog" :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
      <el-form inline class="px10" ref="ruleFormRef" :model="ruleForm" :rules="rules"   :disabled="dialogDatas?.type == 'check'">
        <div>
          <p class="mb1 font-bold text-base">基础信息</p>
          <!-- <template> -->
            <el-form-item label="公司名称" prop="orgName">
              <el-input v-model="ruleForm.orgName" placeholder="请输入公司名称" clearable />
            </el-form-item>
            <el-form-item label="行业类型" prop="industryType" >
              <el-select v-model="ruleForm.industryType" class="w-full" placeholder="请选择行业类型" >
                <el-option v-for="(item) in dialogDatas.industryTyeEnumDatas" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在地区" prop="districtId" v-if="showOrg">
              <el-cascader v-model="diqu.array" @change="handleChange" :options="options" ref="cascaderAddr" clearable placeholder="请选择所在地区" />
            </el-form-item>
            <el-form-item label="详细地址" prop="addressDetails">
              <el-input v-model="ruleForm.addressDetails" placeholder="请输入详细地址" clearable />
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="ruleForm.contactPerson" placeholder="请输入联系人" clearable />
            </el-form-item>
            <el-form-item label="职位">
              <el-input v-model="ruleForm.position" placeholder="请输入职位" clearable />
            </el-form-item>
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="ruleForm.phoneNumber" placeholder="请输入手机号码" clearable maxlength="11" />
            </el-form-item>
            <el-form-item label="微信">
              <el-input v-model="ruleForm.wechat" placeholder="请输入微信" clearable />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="ruleForm.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
          <!-- </template> -->
        </div>
        <!-- 公司详情 -->
        <div>
        <p class="mb1 font-bold text-base">公司详情</p>
        <!-- <el-form-item label="公司营业执照" class="is-required">
           
        </el-form-item> -->
        <el-form-item
        label="公司营业执照"
    
      >
      <!-- prop="businessLicense"
        :rules="[
        {
          required: true,
          message: '请上传公司营业执照',
        }
      ]" -->
        <el-upload
          class="avatar-uploader"
          list-type="picture-card"
          :show-file-list="true"
          :multiple="false"
          :limit="1"
          :file-list="fileList.array"
          :action="uploadUrl"
          name="files"
          @success="handleSuccess"
          @remove="handleRemove"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
        >
          <template #default>
            <el-icon>
              <Plus />
            </el-icon>
          </template>
        </el-upload>
        <el-dialog v-model="dialogVisibleimg">
          <img
            w-full
            :src="dialogImageUrl"
            alt="Preview Image"
          />
        </el-dialog>

      </el-form-item>
        <el-form-item label="邮编">
          <el-input v-model="ruleForm.postalCode" placeholder="请输入邮编" clearable />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="ruleForm.companyPhone" placeholder="请输入电话" clearable maxlength="11" />
        </el-form-item>
        <el-form-item label="网址">
          <el-input v-model="ruleForm.website" placeholder="请输入网址" clearable maxlength="30" />
        </el-form-item>
        <el-form-item label="公司介绍/备注" class="gsjs">
          <el-input v-model="ruleForm.companyDescription" placeholder="请输入公司介绍/备注" type="textarea" maxlength="300" show-word-limit clearable/>
        </el-form-item>
      </div>
      <div>
        <!-- 财务信息 -->
        <p class="mb1 font-bold text-base">财务信息</p>
        <el-form-item label="税号" prop="taxIdOrOrgCode">
          <el-input v-model="ruleForm.taxIdOrOrgCode" placeholder="请输入税号" clearable maxlength="30" minlength="15"/>
        </el-form-item>
        <el-form-item label="发票抬头">
          <el-input v-model="ruleForm.invoiceTitle" placeholder="请输入发票抬头" clearable />
        </el-form-item>
        <el-form-item label="开户银行">
          <el-input v-model="ruleForm.bankName" placeholder="请输入开户银行" clearable />
        </el-form-item>
        <el-form-item label="银行账号">
          <el-input v-model="ruleForm.bankAccount" placeholder="请输入银行账号" clearable maxlength="20" minlength="15" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="ruleForm.telephone" placeholder="请输入电话号码" clearable maxlength="11" oninput="value=value.replace(/[^\d]/g,'')"  />
        </el-form-item>
        <el-form-item label="单位地址">
          <el-input v-model="ruleForm.companyAddress" placeholder="请输入单位地址" clearable />
        </el-form-item>
      </div>
      <div>
        <!-- 组织ID -->
        <p class="mb1 font-bold text-base">组织信息</p>
        <el-form-item label="组织ID">
          <el-input v-model="ruleForm.id" placeholder="请输入组织ID" disabled="true" clearable maxlength="10" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="我方销售人员" prop="salesPersonId" v-if="showOrg">
          <el-select v-model="ruleForm.salesPersonId" class="w-full" placeholder="请选择我方销售人员" >
            <el-option v-for="(item) in dialogDatas.salesOptionsDatas" :key="item.id" :label="item.employeeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户级别" prop="customerLevel" v-if="showOrg">
          <el-select v-model="ruleForm.customerLevel" class="w-full" placeholder="请选择客户级别" >
            <el-option v-for="(item) in dialogDatas.cutomerLevelEnumDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="合作开始时间" prop="cooperationStartDate" v-if="showOrg">
          <el-date-picker
            v-model="ruleForm.cooperationStartDate"
            type="date"
            placeholder="请输入合作开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="机构类型" prop="institutionType" v-if="showOrg">
          <el-select v-model="ruleForm.institutionType" class="w-full" placeholder="请选择机构类型" >
            <el-option v-for="(item) in dialogDatas.institutionTypeEnumDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账期额度" prop="creditLimitPoints">
          <el-input v-model="ruleForm.creditLimitPoints" placeholder="请输入账期额度" clearable maxlength="6" oninput="value=value.replace(/[^\d]/g,'')"  />
        </el-form-item>
        <el-form-item label="管理员手机号" prop="adminPhone">
          <el-input v-model="ruleForm.adminPhone" placeholder="请输入组织管理员手机号" clearable maxlength="11" oninput="value=value.replace(/[^\d]/g,'')"  />
          <!-- <div v-if="!isValidPhone" style="color: red;">手机号码格式不正确</div> -->
        </el-form-item>
        <el-form-item label="来源" prop="source" v-if="showOrg">
          <el-select v-model="ruleForm.source" class="w-full" placeholder="请选择来源" >
            <el-option v-for="(item) in dialogDatas.institutionSourceEnumDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </div>
      </el-form>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer flex justify-center my6" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer flex justify-center my6" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { watch,ref, reactive, onBeforeMount, toRefs,computed } from 'vue';
import { getEnumListRequest, salesOptionsRequest } from '@/api/common';
import { getOrgDetailRequest, addOrgRequest,editOrgRequest } from '@/api/cooperation';
import type { FormInstance, FormRules } from 'element-plus';
import regionData from '@/assets/json/regionData.json';
const options = ref(regionData);
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible','handleFormValue']);
const visible = ref(false);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  provinceId: '',
  cityId: '',
  districtId: '',
  orgName: null,
  industryType: '',
  area: '',
  postalCode: '',
  contactPerson: '',
  position: '',
  phoneNumber: '',
  wechat: '',
  email: '',
  // 公司信息
  businessLicense: '',
  addressDetails: '',
  companyPhone: '',
  website: '',
  companyDescription: '',
  // 财务信息
  taxIdOrOrgCode: '',
  invoiceTitle: '',
  bankName: '',
  bankAccount: '',
  telephone: '',
  companyAddress: '',
  // 组织信息
  id:null,
  salesPersonId: null,
  customerLevel: '',
  cooperationStartDate: '',
  institutionType: '',
  creditLimitPoints: '',
  adminPhone:'',
  source:'',
})
// let chanFormValue = reactive({});
watch(dialogDatas, (newVal) => {
  // newVal.panelDatas.forEach((panelItem: { title: ''; datas: [] }) => {
  //   panelItem.datas.forEach((d: { value: any[]; type: string; eName: string | number | any[] }) => {
  //     if (d.value) {
  //       if (d.type === 'cascader') {
  //         d.keys.forEach((item: string | number, i: number) => {
  //           chanFormValue[item] = d.value[i];
  //         });
  //         return;
  //       }else
  //        if (d.type === 'upload') {
  //         if(newVal.type !== 'add'){//查看
  //           fileList.array=[{url: d.value, name:  Math.floor(Math.random() * 10) + 1}]
  //         }else{//新增
  //           d.value = fileList.array
  //         }
  //      return
  //     }
  //       chanFormValue[d.eName] = d.value;
  //     }else{
  //      const noValue= Object.keys(chanFormValue).includes(d.eName)
  //       if(noValue){
  //         delete  chanFormValue[d.eName]
  //       }
  //   }
  //     emits('handleFormValue', chanFormValue);
  //   });
  // });
},{deep:true});
// 校验
const rules = reactive<FormRules>({
  orgName: [{ required: true, message: '请输入公司名称', trigger: 'change' },],
  industryType: [{ required: true, message: '请选择行业类型', trigger: 'change' }],
  districtId: [{ required: true, message: '选择所在地区', trigger: 'change' }],
  addressDetails: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'change' }],
  phoneNumber: [{ required: true, message: '请输入手机号码', trigger: 'change' },],
  taxIdOrOrgCode: [{ required: true, message: '请输入税号', trigger: 'change' }],
  salesPersonId: [{ required: true, message: '选择销售人员', trigger: 'change' }],
  customerLevel: [{ required: true, message: '请选择客户级别', trigger: 'change' }],
  cooperationStartDate: [{ required: true, message: '请选择合作开始时间', trigger: 'change' },],
  institutionType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
  creditLimitPoints: [{ required: true, message: '请输入账期额度', trigger: 'change' }],
  adminPhone: [{ required: true, message: '请输入管理员手机号', trigger: 'change' }],
  source: [{ required: true, message: '请选择来源', trigger: 'change' }],
  // { validator: checkAge, trigger: 'blur' }
})
// let diqu=reactive(Array:[])
let diqu = reactive({ array: [] });
const value = ref([])
const handleChange = (value) => {
  ruleForm.provinceId=value[0]
  ruleForm.cityId=value[1]
  ruleForm.districtId=value[2]
  console.log(value,"sdfsfasdf")
}
const dialogVisibleimg = ref(false);
const dialogImageUrl = ref([]);
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisibleimg.value = true;
  console.log(dialogVisibleimg.value,"dialogVisibleimg.value")
};
let fileList = reactive({ array: [] });
const uploadUrl = ref('admin/common/uploadFileByPublic');
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/jpg' || rawFile.type == 'image/png'|| rawFile.type == 'image/bmp')) {
    ElMessage.error('请上传jpeg、jpg、png、bmp格式文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传文件不能超过 5MB!')
    return false
  }
  return true
}
const handleSuccess = (response, file, fileList) => {
  ruleForm.businessLicense = response.data.url[0]
  console.log(response, file, fileList,"response, file, fileList")
};
const handleRemove = ()=> {
  ruleForm.businessLicense = ''
  
}
// const isValidPhone = computed(() => /^1[3-9]\d{9}$/.test(ruleForm.responsiblePersonPhone));
 
// function validatePhoneNumber(event) {
//   // 限制只能输入数字
//   ruleForm.responsiblePersonPhone = event.target.value.replace(/\D/g, '');
// }

//     const handleChange= async (file, fileList) => {

// };
//提交
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let Url = dialogDatas.value.type == 'add' ? addOrgRequest : editOrgRequest;
      console.log(fileList.array, ruleForm);
      // ruleForm.businessLicense = fileList.array[0] || ''
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')
    } else {
      console.log('保存失败', fields)
    }
  })
}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}

var cutomerLevelEnumDatas = reactive([{name: "", id: null}]); //客户级别下拉数据
var institutionSourceEnumDatas = reactive([{name: "", id: null}]); //客户级别下拉数据
var institutionTypeEnumDatas = reactive([{name: "", id: null}]); //客户类型下拉数据
var industryTyeEnumDatas = reactive([{name: "", id: null}]); //行业类型下拉数据
// var orgTypeEnumDatas = reactive([]); //组织类型下拉数据
var salesOptionsDatas = reactive([{name: "", id: null}]); //我方销售人员下拉数据
var showOrg = ref(false)
/* 获取客户级别下拉数据 */
const getCutomerLevelEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'CutomerLevelEnum' });
  return cutomerLevelEnumDatas = data.data;
};
/* 获取来源下拉数据 */
const getInstitutionSourceEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionSourceEnum' });
  return institutionSourceEnumDatas = data.data;
};

/* 获取客户类型下拉数据 */
const getInstitutionTypeEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionTypeEnum' });
  return institutionTypeEnumDatas = data.data;
};

/* 获取行业类型下拉数据 */
const getIndustryTyeEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'IndustryTyeEnum' });
  
  industryTyeEnumDatas = data.data;
  console.log(industryTyeEnumDatas,"industryTyeEnumDatas")
};
/* 获取组织类型下拉数据 */
// const getOrgTypeEnumDatas = async () => {
//   const data: any = await getEnumListRequest({ enumName: 'InstitutionTypeEnum' });
//   orgTypeEnumDatas = data.data;
// };

/* 获取组织类型下拉数据 */
const getSalesOptionsDatas = async (datas:{name:''}) => {
  const data: any = await salesOptionsRequest(datas);
  return salesOptionsDatas = data.data;
};

// 获取详情
const getDetailsFun = async () => {
  const data: any = await getOrgDetailRequest({ orgId: dialogDatas.value.datas.id });
  let res = data.data
  console.log(res.provinceId,"resresresresres")
  diqu.array=[res.provinceId.toString(),res.cityId.toString(),res.districtId.toString()]
  console.log(diqu.array,"dddddd")
  ruleForm.orgName = res.orgName
  ruleForm.industryType = res.industryType
  ruleForm.area = res.area
  ruleForm.postalCode = res.postalCode
  ruleForm.contactPerson = res.contactPerson
  ruleForm.position = res.position
  ruleForm.phoneNumber = res.phoneNumber
  ruleForm.wechat = res.wechat
  ruleForm.email = res.email
  ruleForm.provinceId=res.provinceId
  ruleForm.cityId=res.cityId
  ruleForm.districtId=res.districtId
  // 公司信息
  ruleForm.businessLicense = res.businessLicense
 
  ruleForm.addressDetails = res.addressDetails
  ruleForm.companyPhone = res.companyPhone
  ruleForm.website = res.website
  ruleForm.companyDescription = res.companyDescription
  // 财务信息
  ruleForm.taxIdOrOrgCode = res.taxIdOrOrgCode
  ruleForm.invoiceTitle = res.invoiceTitle
  ruleForm.bankName = res.bankName
  ruleForm.bankAccount = res.bankAccount
  ruleForm.telephone = res.telephone
  ruleForm.companyAddress = res.companyAddress
  // 组织信息
  ruleForm.id = res.id
  ruleForm.salesPersonId = res.salesPersonId
  ruleForm.customerLevel = res.customerLevel
  ruleForm.cooperationStartDate = res.cooperationStartDate
  ruleForm.institutionType = res.institutionType
  ruleForm.creditLimitPoints = res.creditLimitPoints
  ruleForm.adminPhone = res.adminPhone
  ruleForm.source = res.source
  showOrg.value=true
  if(dialogDatas.value.type !== 'add'){ //查看
    if (!res.businessLicense) return
    fileList.array=[{url: res.businessLicense, name:  Math.floor(Math.random() * 10) + 1}]
    // fileList.array=res.businessLicense
    console.log(fileList.array,"fileList.array")
  }
  
}

onBeforeMount( () => {
  getCutomerLevelEnumDatas(); //客户级别下拉数据
  getInstitutionSourceEnumDatas(); //获取来源下拉数据
  getInstitutionTypeEnumDatas(); //获取客户类型下拉数据
  getIndustryTyeEnumDatas(); //获取行业类型下拉数据
  // getOrgTypeEnumDatas(); //获取组织类型下拉数据
  getSalesOptionsDatas({name:''}); //获取我方销售人员下拉数据
  if (dialogDatas.value.type == 'add') {
    // getMenuList()
    showOrg.value=true
  } else {
    getDetailsFun()
  }
})
</script>

<style lang="scss" >
.cooperationDialog {
  .el-form-item {
    display: inline-block;
  }
  .el-form-item__content {
    width: 200px !important;
  }
  .avatar-uploader {
    width: 151px;
    height: 151px;

    overflow: hidden;
  }
  .gsjs{
    .el-form-item__content {
      width: 450px !important;
    }
  }
}
.el-dialog__footer{
  text-align: center;
}
</style>
